<template>
    <div style=" width: 210mm;margin: 0 auto;background-color: #fff;padding: 20px;min-height: calc(100vh - 40px);">
        <!-- <router-link to="/main/renshi/renshizhidu" style="position: absolute; top: 10px; left: 10px;">返回</router-link> -->
        <div style="display: flex;justify-content: space-between;padding-top: 20px;">
            <span>
                <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            </span>
            <span>
                <el-button type="success" icon="el-icon-check" v-if="!isView" @click="saveData">保存</el-button>
                <el-button type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <!-- <button @click="printToPDF">打印PDF</button> -->

                <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <div class="notice-container">
            <!-- 通知联 -->
            <div class="notice">
                <h2 style="text-align: center;">续订劳动合同通知书（通知联）</h2>
                <hr style="border-color: black; border: 1px solid black; margin: 15px 0px;">
                <p><input type="text" v-model="applicant" :disabled="isView">员工（身份证号码： <input v-model="idNumber"
                        :disabled="isView"> ）：</p>
                <p style="margin-left: 35px;">您与我司的劳动合同即将于
                    <el-date-picker v-model="contractEndDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日到期，公司拟定于
                    <el-date-picker v-model="renewStartDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日至
                    <el-date-picker v-model="renewEndDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日期间以不低于原劳动合同约定的条件与您续订劳动合同。
                </p>
                <p style="margin-left: 35px;">请您在
                    <el-date-picker v-model="replyDeadline" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日前向我司
                </p>
                <p>
                    书面回复您对本通知书的意见，若您未按时提供书面回复的，视为您不同意在劳动合同到期后续签，劳动关系将于劳动合同到期后自动终止。
                </p>
                <p style="margin-left: 35px;">您是否同意续签劳动合同？
                    <el-radio-group v-model="isAgreeRenew" :disabled="isView">
                        <el-radio label="是">是</el-radio>
                        <el-radio label="否">否</el-radio>
                    </el-radio-group>
                </p>
                <p style="margin-left: 35px;">您不同意续签的理由是： <el-input type="textarea" v-model="disagreeReason"
                        :disabled="isView" :rows="3"></el-input></p>
                <p style="margin-left: 35px;">您对本通知书的其他意见： <el-input type="textarea" v-model="otherOpinions"
                        :disabled="isView" :rows="3"></el-input></p>
                <p>（请员工仔细阅读以上内容，本通知书一式三联，通知联由公司留存，回执联由员工签署回复意见后交公司留档，员工留存联交由员工持有。）</p>
                <p style="text-align: right;">员工签名： <el-input v-model="employeeSignature" :disabled="isView"
                        style="width: 200px; display: inline-block;"></el-input></p>
                <p style="text-align: right;">日期：
                    <el-date-picker v-model="noticeDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                </p>
            </div>
            <p class="footer"><span>表单编号及版本：AM-JY-280 A/1</span> <span>保存期限：长期</span></p>

            <!-- 回执联 -->
            <div class="notice">
                <h2 style="text-align: center;">续订劳动合同通知书（回执联）</h2>
                <hr style="border-color: black; border: 1px solid black; margin: 15px 0px;">
                <p><input type="text" v-model="applicant" name="" id="">员工（身份证号码： <input v-model="idNumber"> ）：</p>
                <p style="margin-left: 35px;">您与我司的劳动合同即将于
                    <el-date-picker v-model="contractEndDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日到期，公司拟定于
                    <el-date-picker v-model="renewStartDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日至
                    <el-date-picker v-model="renewEndDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日期间以不低于原劳动合同约定的条件与您续订劳动合同。
                </p>
                <p style="margin-left: 35px;">请您在
                    <el-date-picker v-model="replyDeadline" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                    日前向我司
                </p>
                <p>书面回复您对本通知书的意见，若您未按时提供书面回复的，视为您不同意在劳动合同到期后续签，劳动关系将于劳动合同到期后自动终止。</p>
                <p style="margin-left: 35px;">您是否同意续签劳动合同？
                    <input type="radio" v-model="isAgreeRenew" value="yes"> 是
                    <input type="radio" v-model="isAgreeRenew" value="no"> 否
                </p>
                <p style="margin-left: 35px;">您不同意续签的理由是： <textarea cols="90" v-model="disagreeReason"></textarea></p>
                <p style="margin-left: 35px;">您对本通知书的其他意见： <textarea cols="88" v-model="otherOpinions"></textarea></p>
                <p>（请员工仔细阅读以上内容，本通知书一式三联，通知联及回执联由公司留存，员工留存联交由员工。）</p>
                <p style="text-align: right;">员工签名： <input style="border: 0px;" v-model="employeeSignature"> </p>
                <p style="text-align: right;">回复日期：
                    <el-date-picker v-model="replyDate" type="date" :disabled="isView" value-format="yyyy-MM-dd"
                        style="width: 150px;" placeholder="选择日期">
                    </el-date-picker>
                </p>
            </div>
            <p class="footer"><span>表单编号及版本：AM-JY-280 A/1</span> <span>保存期限：长期</span></p>
        </div>
    </div>
</template>

<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { getRenewContractNoticeById, saveRenewContractNotice } from '@/api/renewContractNotice'

export default {
    data() {
        return {
            isView: false,
            formData: {
                id: null,
                applicant: '',
                idNumber: '',
                contractEndDate: '',
                renewStartDate: '',
                renewEndDate: '',
                replyDeadline: '',
                isAgreeRenew: '',
                disagreeReason: '',
                otherOpinions: '',
                employeeSignature: '',
                noticeDate: '',
                replyDate: ''
            },
            formDatas: {
                applicant: '',
                idNumber: '',
                contractEndDate: '',
                renewStartDate: '',
                renewEndDate: '',
                replyDeadline: '',
                isAgreeRenew: '',
                disagreeReason: '',
                otherOpinions: '',
                employeeSignature: '',
                noticeDate: '',
                replyDate: ''
            },
        };
    },
    computed: {
        // 员工姓名
        applicant: {
            get() {
                return this.formData.applicant;
            },
            set(value) {
                this.formData.applicant = value;
            }
        },
        // 身份证号
        idNumber: {
            get() {
                return this.formData.idNumber;
            },
            set(value) {
                this.formData.idNumber = value;
            }
        },
        // 合同到期日期
        contractEndDate: {
            get() {
                return this.formData.contractEndDate;
            },
            set(value) {
                this.formData.contractEndDate = value;
            }
        },
        // 续签开始日期
        renewStartDate: {
            get() {
                return this.formData.renewStartDate;
            },
            set(value) {
                this.formData.renewStartDate = value;
            }
        },
        // 续签结束日期
        renewEndDate: {
            get() {
                return this.formData.renewEndDate;
            },
            set(value) {
                this.formData.renewEndDate = value;
            }
        },
        // 回复截止日期
        replyDeadline: {
            get() {
                return this.formData.replyDeadline;
            },
            set(value) {
                this.formData.replyDeadline = value;
            }
        },
        // 是否同意续签
        isAgreeRenew: {
            get() {
                return this.formData.isAgreeRenew;
            },
            set(value) {
                this.formData.isAgreeRenew = value;
            }
        },
        // 不同意续签理由
        disagreeReason: {
            get() {
                return this.formData.disagreeReason;
            },
            set(value) {
                this.formData.disagreeReason = value;
            }
        },
        // 其他意见
        otherOpinions: {
            get() {
                return this.formData.otherOpinions;
            },
            set(value) {
                this.formData.otherOpinions = value;
            }
        },
        // 员工签名
        employeeSignature: {
            get() {
                return this.formData.employeeSignature;
            },
            set(value) {
                this.formData.employeeSignature = value;
            }
        },
        // 通知日期
        noticeDate: {
            get() {
                return this.formData.noticeDate;
            },
            set(value) {
                this.formData.noticeDate = value;
            }
        },
        // 回复日期
        replyDate: {
            get() {
                return this.formData.replyDate;
            },
            set(value) {
                this.formData.replyDate = value;
            }
        }
    },
    created() {
        const { id, type } = this.$route.query
        if (id) {
            this.fetchData(id)
        }
        this.isView = type === 'view'
    },
    methods: {
        printForm() {
            window.print()
        },

        validateIdNumber(idNumber) {
            const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            return reg.test(idNumber)
        },
        formatDate(date) {
            if (!date) return ''
            if (typeof date === 'string') {
                // 如果已经是yyyy-MM-dd格式，直接返回
                if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
                    return date
                }
                // 尝试解析其他格式的日期字符串
                const d = new Date(date)
                if (isNaN(d.getTime())) {
                    return ''
                }
                return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
            }
            // 处理Date对象
            const d = new Date(date)
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        },
        fetchData(id) {
            getRenewContractNoticeById(id).then(response => {
                // 格式化日期字段
                const formattedData = {
                    ...response.data,
                    contractEndDate: this.formatDate(response.data.contractEndDate),
                    renewStartDate: this.formatDate(response.data.renewStartDate),
                    renewEndDate: this.formatDate(response.data.renewEndDate),
                    replyDeadline: this.formatDate(response.data.replyDeadline),
                    noticeDate: this.formatDate(response.data.noticeDate),
                    replyDate: this.formatDate(response.data.replyDate)
                }
                this.formData = formattedData
                this.formDatas = { ...formattedData }
            })
        },
        validateForm() {
            if (!this.formData.applicant) {
                this.$message({
                    type: 'warning',
                    message: '请输入员工姓名'
                })
                return false
            }
            if (!this.formData.idNumber) {
                this.$message({
                    type: 'warning',
                    message: '请输入身份证号码'
                })
                return false
            }
            if (!this.validateIdNumber(this.formData.idNumber)) {
                this.$message({
                    type: 'warning',
                    message: '请输入正确的身份证号码格式'
                })
                return false
            }
            if (!this.formData.contractEndDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择合同到期日期'
                })
                return false
            }
            if (!this.validateIdNumber(this.formData.idNumber)) {
                this.$message({
                    type: 'warning',
                    message: '请输入正确的身份证号码格式'
                })
                return false
            }
            if (!this.formData.renewStartDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择续签开始日期'
                })
                return false
            }
            if (!this.formData.renewEndDate) {
                this.$message({
                    type: 'warning',
                    message: '请选择续签结束日期'
                })
                return false
            }
            if (!this.formData.replyDeadline) {
                this.$message({
                    type: 'warning',
                    message: '请选择回复截止日期'
                })
                return false
            }
            return true
        },
        validateIdNumber(idNumber) {
            const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
            return reg.test(idNumber)
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/xdlaodonght/xdlaodonghtList')
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        },
        saveData() {
            if (!this.validateForm()) {
                return
            }
            const data = {
                ...this.formData,
                replyDate: this.formDatas.replyDate // 保存时使用回执联的回复日期
            }
            saveRenewContractNotice([data]).then(() => {
                this.$message({
                    type: 'success',
                    message: '保存成功！'
                })
                this.$router.push('/main/renshi/renshizhidu/xdlaodonght/xdlaodonghtList')
            }).catch(error => {
                this.$message({
                    type: 'error',
                    message: '保存失败：' + error.message
                })
            })
        },
        printToPDF() {
            const doc = new jsPDF('p', 'pt', 'a4');
            const element = document.querySelector('.notice-container');
            html2canvas(element).then((canvas) => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 522;
                const pageHeight = 841.89;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;
                let positionY = 0;
                if (imgHeight >= pageHeight) {
                    let leftHeight = imgHeight;
                    while (leftHeight >= pageHeight) {
                        doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, pageHeight);
                        positionY += pageHeight;
                        doc.addPage();
                        leftHeight -= pageHeight;
                    }
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, leftHeight);
                } else {
                    doc.addImage(imgData, 'PNG', 40, positionY, imgWidth, imgHeight);
                }
                doc.save('续订劳动合同通知书.pdf');
            });
        }
    }
};
</script>

<style scoped>
.notice-container {
    margin-top: 20px;
    line-height: 45px;
    text-align: left;
    margin: 0px auto;
}

.notice {
    /* border: 1px solid #ccc; */
    padding: 20px;
    margin-bottom: 20px;
    text-align: left;
    page-break-inside: avoid;
    /* 避免内容在中间分页 */
}

.footer {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    page-break-inside: avoid;
    /* 避免内容在中间分页 */
    color: #757575;
}

.el-date-picker {
    width: 150px !important;
}

::v-deep .el-textarea__inner {
    border: none;
}

.el-textarea {
    width: 100%;
    margin: 10px 0;
    border: none;
}

::v-deep .el-input__inner {
    border: 0px;
}

@media print {
    .notice-container {
        page-break-after: always;
        /* 在每个通知联后分页 */
    }

    .notice-container:last-child {
        page-break-after: avoid;
        /* 最后一个通知联后不分页 */
    }
}

/* button {
    padding: 5px 10px;
    margin: 10px;
} */
input[type="radio"] {
    height: 13px;
}

input {
    border: 0px;
}

@media print {

    body,
    html {
        margin: 0;
        padding: 0;
    }

    .el-button {
        display: none !important;
    }

    .checkbox {
        display: none;
    }

    .leave-adjustment-form {
        margin: 0;
        padding: 0;
        page-break-inside: avoid;
    }

    table {
        page-break-inside: avoid;
        border-collapse: collapse;
        box-shadow: none;
    }

    table th,
    table td {
        border: 1px solid #000;
    }

    input,
    textarea {
        border: none !important;
        background-color: transparent !important;
        text-align: center;
        resize: none !important;
    }

    ::v-deep .el-textarea__inner {
        resize: none !important;
    }

    ::v-deep .el-input__icon {
        display: none;
    }

    .instructions {
        page-break-before: avoid;
    }
}
</style>